# -*- coding:utf-8 -*-

import csv
from pymongo import MongoClient

client = MongoClient('127.0.0.1', 27017)
db = client["Test"]
table = db["aa233网校_证券从业及专项"]
# datas = table.find({"$and":[{"type": ""}, {"title": ""}]})
datas = table.find()
line = 0
previous = ""
for d in datas:
    dict_data = dict()
    dict_data['标题'] = d.get('title')
    dict_data['类型'] = d.get('type')
    dict_data['章'] = d.get('part')
    dict_data['节'] = d.get('part_class')
    dict_data['主题号'] = d.get('examId')
    dict_data['次题号'] = d.get('examId_c')
    dict_data['次题号1'] = d.get('subexamId')
    dict_data['题型'] = d.get('examTypeName')
    dict_data['题干'] = d.get('content')
    dict_data['问题'] = d.get('returnQuestion')
    dict_data['分析'] = d.get('analysis')
    dict_data['答案'] = d.get('answer').replace(",", "")
    dict_data['选项A'] = d.get('option_1')
    dict_data['选项B'] = d.get('option_2')
    dict_data['选项C'] = d.get('option_3')
    dict_data['选项D'] = d.get('option_4')
    # dict_data['选项E'] = d.get('option_5')
    dict_data['知识点'] = d.get('zsd')
    dict_data['页码'] = d.get('ym')
    print(str(dict_data))
    if dict_data['节'] != "":
        path = "./csv/" + dict_data['标题'] + "_" + dict_data['章'] + "_" + dict_data['节'] + ".csv"
    else:
        path = "./csv/" + dict_data['标题'] + "_" + dict_data['章'] + ".csv"

    if previous != path:
        previous = path
        with open(path, "a+", encoding="utf-8-sig", newline="") as f:
            csv_writer = csv.writer(f)
            csv_writer.writerow(["标题", "类型", "章", "节", "主题号", "次题号", "次题号1", "题型",
                                 "题干", "问题", "分析", "答案", "选项A", "选项B", "选项C", "选项D",
                                 "知识点", "页码"])

    with open(path, "a", encoding="utf-8-sig", newline="") as csvfile:
        fileheader = ["标题", "类型", "章", "节", "主题号", "次题号", "次题号1", "题型",
                      "题干", "问题", "分析", "答案", "选项A", "选项B", "选项C", "选项D", "知识点", "页码"]
        writer = csv.DictWriter(csvfile, fieldnames=fileheader)
        writer.writerow(dict_data)
    line += 1
    print(line)